package service

import (
	"errors"
	"flag"
	"gitee.com/Frank098/devops-app-mgt/utils/log"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
	metricsvs "k8s.io/metrics/pkg/client/clientset/versioned"
	"path/filepath"
)

// K8s 用于初始化k8s client
var K8s k8s

type k8s struct {
	ClientSet *kubernetes.Clientset
	Mc        *metricsvs.Clientset
	Dc        *dynamic.DynamicClient
	Config    *rest.Config
}

func (k *k8s) KubernetesInit(kubeConfig string) (err error) {
	// 将kuberconfig文件转换成rest.config对象
	config, err := k.KubernetesClientInit(kubeConfig)
	if err != nil {
		return errors.New("获取K8s配置失败, " + err.Error())
	} else {
		log.Info("获取K8s配置 成功!")
	}
	k.Config = config

	// 根据rest.config对象,new一个clientset出来
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		return errors.New("获取K8s配置失败, " + err.Error())
	} else {
		log.Info("创建K8s client 成功!")
	}
	k.ClientSet = clientset

	mc, err := metricsvs.NewForConfig(config)
	if err != nil {
		return errors.New("获取metrics client配置失败, " + err.Error())
	} else {
		log.Info("创建metrics client 成功!")
	}
	k.Mc = mc

	dc, err := dynamic.NewForConfig(config)
	if err != nil {
		return errors.New("获取dynamic client配置失败, " + err.Error())
	} else {
		log.Info("创建dynamic client 成功!")
	}
	k.Dc = dc
	return nil
}

func (k *k8s) KubernetesClientInit(KubeConfigPath string) (config *rest.Config, err error) {
	var kubeConfig *string
	if home := KubeConfigPath; home != "" {
		kubeConfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
	} else {
		kubeConfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()
	config, err = clientcmd.BuildConfigFromFlags("", *kubeConfig)
	if err != nil {
		log.Errorf(err.Error())
		return nil, err
	}
	return config, nil
}
